package com.zby.service.imp;

import com.zby.common.minio.MinioFuntion;
import com.zby.common.utils.JwtUtils;
import com.zby.mapper.UserInfoMapper;
import com.zby.mapper.UserMapper;
import com.zby.model.pojo.User;
import com.zby.model.pojo.UserInfo;
import com.zby.service.UserInfoService;
import com.zby.vo.UserInfoVo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wuyanzhu
 */
@Slf4j
@Service
public class UserInfoServiceImp implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MinioFuntion minioFuntion;
    @Autowired
    private JwtUtils  jwtUtils;


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateUserInfo(UserInfoVo userInfo) {
        log.info("开始更新用户信息，用户ID：{}", userInfo.getUserId());
        log.info("查看数据{}", userInfo.getSex());

        if (userInfo == null || userInfo.getUserId() == null || userInfo.getUserId() == 0) {
            log.error("非法用户信息参数");
            throw new IllegalArgumentException("Invalid userInfo");
        }
        // 在更新前添加校验
        if (userMapper.selectById(userInfo.getUserId()) == null) {
            log.error("尝试更新不存在的用户，用户ID：{}", userInfo.getUserId());
            throw new IllegalArgumentException("用户不存在");
        }
        // 接收旧的图片地址
        String oldAvatar = userInfo.getAvatar();
        // 查找临时图片并复制到图片存储桶
        try {
            if(oldAvatar!=null ){
                // 需要截取的前缀（包含最后的斜杠）
                String prefix = "http://192.168.213.129:9000/temporary-files/";
                String newAvatarPath = oldAvatar.substring(prefix.length());

                String imgUrl = minioFuntion.transferBetweenBuckets("temporary",
                        "avatar",
                        newAvatarPath);
                    System.out.println(imgUrl);
                if (imgUrl == null) {
                    log.error("临时图片不存在，用户ID：{}", userInfo.getUserId());
                    throw new RuntimeException("临时图片不存在");
                }
                userInfo.setAvatar(imgUrl);
            //   删除临时图片
                    minioFuntion.deleteFile(oldAvatar);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        User user = new User();
        user.setId(userInfo.getUserId());
        user.setAuthorName(userInfo.getAuthorName());
        user.setEmail(userInfo.getEmail());
        user.setAvatar(userInfo.getAvatar());
        UserInfo userInfoEntity = new UserInfo();
        BeanUtils.copyProperties(userInfo, userInfoEntity);


        int userUpdateCount = userMapper.updateUser(user);
        int userInfoUpdateCount = userInfoMapper.updateUserInfo(userInfoEntity);

        if (userUpdateCount == 0 || userInfoUpdateCount == 0) {
            log.error("用户信息更新失败，用户ID：{}", userInfo.getUserId());

            throw new RuntimeException("用户信息更新失败");
        }
        log.info("用户信息更新成功，用户ID：{}", userInfo.getUserId());
    }

    @Override
    public UserInfoVo selectUserInfo() {

        // 从 Spring Security 上下文获取当前认证用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }

        // 假设你的 Principal 是用户 ID（String 类型）
        String userId = (String) authentication.getPrincipal();
         return  userInfoMapper.selectUserInfo(Integer.parseInt(userId.toString()));
    }


}